package com.whu.zj;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Typeface;

import com.google.gson.Gson;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.orm.SugarApp;
import com.orm.SugarRecord;

import java.util.ArrayList;
import java.util.List;

import chat.network.tcp.PushService;
import inter.SimpleInfo;
import main.dto.MobileUserDto;
import main.dto.WaterPlant;
import model.OwnUser;
import utils.ACache;


/**
 * Created by Administrator on 2016/2/21.
 */
public class MyApplication extends SugarApp {
    public static boolean isExitMust = false;
    // 应用程序单例，使用Context方便
    public static MyApplication shareApp;
    public static DisplayImageOptions options;
    public static ACache aCache = null;
    public static MobileUserDto mobileUserDto;
    public static WaterPlant realPlant;

    public static List<String> realPlantType;

    public static List<String> someType = new ArrayList<String>();//最终的结果



    static {
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.defalut_img) //设置图片在下载期间显示的图片
                .showImageForEmptyUri(R.drawable.defalut_img)//设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.defalut_img)  //设置图片加载/解码过程中错误时候显示的图片
                .cacheInMemory(true)//设置下载的图片是否缓存在内存中
                .cacheOnDisc(true)//设置下载的图片是否缓存在SD卡中
                .considerExifParams(true)  //是否考虑JPEG图像EXIF参数（旋转，翻转）
                .imageScaleType(ImageScaleType.EXACTLY)//设置图片以如何的编码方式显示
                .bitmapConfig(Bitmap.Config.RGB_565)//设置图片的解码类型//
                .resetViewBeforeLoading(true)//设置图片在下载前是否重置，复位
                .displayer(new RoundedBitmapDisplayer(20))//是否设置为圆角，弧度为多少
                .displayer(new FadeInBitmapDisplayer(100))//是否图片加载好后渐入的动画时间
                .build();//构建完成
    }

    // 全局Context获得
    public static MyApplication share() {
        return shareApp;
    }

    public static Typeface iconfont;

    @Override
    public void onCreate() {
        super.onCreate();
        // 检查错误
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable ex) {
                ex.printStackTrace();
            }
        });
        shareApp = this;
        UIHandler.uiHandler = new UIHandler();

        aCache = ACache.get(this);

        // 初始化数据库
        initImageLoader(getApplicationContext());

        iconfont = Typeface.createFromAsset(getAssets(), "iconfont.ttf");

        initbasicinfo();
//        initPushServise();
    }

    private void initbasicinfo() {
        Gson gson = new Gson();
        String userbasicinfo = MyApplication.aCache.getAsString(SimpleInfo.USERBASIEINFO);
        if (userbasicinfo != null)
            mobileUserDto = gson.fromJson(userbasicinfo, MobileUserDto.class);
        System.out.println("...");
    }

    public static void initImageLoader(Context context) {
        ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context);
        config.threadPriority(Thread.NORM_PRIORITY - 2);
        config.denyCacheImageMultipleSizesInMemory();
        config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
        config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
        config.tasksProcessingOrder(QueueProcessingType.LIFO);
        config.writeDebugLogs(); // Remove for release app

        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config.build());
    }

    public static OwnUser getOwnUser() {
        OwnUser ownUser = null;
        {
            List<OwnUser> ownUsers = SugarRecord.listAll(OwnUser.class);
            if (!ownUsers.isEmpty()) {
                ownUser = ownUsers.get(0);
            }
        }
        return ownUser;
    }

    // 重置当前选中水厂
    public static void initRealPlant(String plantNum)
    {
        for (WaterPlant waterPlant : MyApplication.mobileUserDto.getWaterPlants()) {
            if (waterPlant.getWaterPlantCode().equals(plantNum)) {
                realPlant = waterPlant;
            }
        }
    }


    // 获取当前水厂
    public static WaterPlant getRealPlant() {
        if (realPlant != null) return realPlant;
        else {
            for (WaterPlant waterPlant : MyApplication.mobileUserDto.getWaterPlants()) {
                if (waterPlant.getWaterPlantCode().equals(mobileUserDto.getWaterUser().getWaterplantNum())) {
                    realPlant = waterPlant;
                }
            }
        }
        return realPlant;
    }

    public static WaterPlant getRealPlantByName() {
        if (realPlant != null) return realPlant;
        else {
            for (WaterPlant waterPlant : MyApplication.mobileUserDto.getWaterPlants()) {
                if (waterPlant.getWaterPlantCode().equals(mobileUserDto.getWaterUser().getWaterplantNum())) {
                    realPlant = waterPlant;
                }
            }
        }
        return realPlant;
    }


    public static List<String> getRealPlantType() {
        if (realPlantType != null) return realPlantType;
        realPlantType = new ArrayList<String>();
        WaterPlant nowPlant = MyApplication.getRealPlant();
        List<String> tempPlantType = MyApplication.mobileUserDto.getWaterPlantTypes();
        List<String> firstType = tempPlantType.subList(0, 8);
//        List<String> supplyPumpType1 = tempPlantType.subList(8,24);
        List<String> supplyPumpType1 = new ArrayList<String>();
        if (nowPlant.getSupplyPumpNum() != 0) {
            supplyPumpType1 = tempPlantType.subList(8, 8 + nowPlant.getSupplyPumpNum());
        }
//        List<String> supplyFlow = tempPlantType.subList(24,30);
        List<String> supplyFlow = new ArrayList<String>();
//        List<String> supllyFlowNum = tempPlantType.subList(30,36);

        List<String> supllyFlowNum = new ArrayList<String>();
        if (nowPlant.getSupplyFlowNum() != 0) {
            supplyFlow = tempPlantType.subList(24, 24 + nowPlant.getSupplyFlowNum());
            supllyFlowNum = tempPlantType.subList(30, 30 + nowPlant.getSupplyFlowNum());

            for (int i = 0;i< nowPlant.getSupplyFlowNum();i++)
            {
                String now_flow = supplyFlow.get(i);
                String now_flownum = supllyFlowNum.get(i);

                String changedFlow = "";
                String changedFlowNum = "";
                switch (i)
                {
                    case 0:
                        changedFlow = MyApplication.mobileUserDto.getNametoname().getFlowmeter1() + now_flow.substring(4);
                        changedFlowNum  = MyApplication.mobileUserDto.getNametoname().getFlowmeter1() + now_flownum.substring(4);
                        break;
                    case 1:
                        changedFlow = MyApplication.mobileUserDto.getNametoname().getFlowmeter2() + now_flow.substring(4);
                        changedFlowNum  = MyApplication.mobileUserDto.getNametoname().getFlowmeter2() + now_flownum.substring(4);

                        break;
                    case 2:
                        changedFlow = MyApplication.mobileUserDto.getNametoname().getFlowmeter3() + now_flow.substring(4);
                        changedFlowNum  = MyApplication.mobileUserDto.getNametoname().getFlowmeter3() + now_flownum.substring(4);

                        break;
                    case 3:
                        changedFlow = MyApplication.mobileUserDto.getNametoname().getFlowmeter4() + now_flow.substring(4);
                        changedFlowNum  = MyApplication.mobileUserDto.getNametoname().getFlowmeter4() + now_flownum.substring(4);


                        break;
                    case 4:
                        changedFlow = MyApplication.mobileUserDto.getNametoname().getFlowmeter5() + now_flow.substring(4);
                        changedFlowNum  = MyApplication.mobileUserDto.getNametoname().getFlowmeter5() + now_flownum.substring(4);


                        break;
                    case 5:
                        changedFlow = MyApplication.mobileUserDto.getNametoname().getFlowmeter6() + now_flow.substring(4);
                        changedFlowNum  = MyApplication.mobileUserDto.getNametoname().getFlowmeter6() + now_flownum.substring(4);


                        break;
                }

                supplyFlow.set(i,changedFlow);
                supllyFlowNum.set(i,changedFlowNum);
            }
        }


        List<String> nextType = tempPlantType.subList(36, 39);
//        List<String> getPump = tempPlantType.subList(39,43);
        List<String> getPump = new ArrayList<String>();
        if (nowPlant.getGetPumpNum() != 0) {
            getPump = tempPlantType.subList(39, 39 + nowPlant.getGetPumpNum());
        }

//        List<String> supplyPumpState = tempPlantType.subList(43,51);
        List<String> supplyPumpState = new ArrayList<String>();
        if (nowPlant.getSupplyPumpNum() != 0) {
            supplyPumpState = tempPlantType.subList(43, 43 + nowPlant.getSupplyPumpNum());
        }
//        List<String> backWind = tempPlantType.subList(51,55);
        List<String> backWind = new ArrayList<String>();
        if (nowPlant.getBackwashFanNum() != 0) {
            backWind = tempPlantType.subList(51, 51 + nowPlant.getBackwashFanNum());
        }

        List<String> endType = tempPlantType.subList(55, 57);


        realPlantType.addAll(firstType);
        realPlantType.addAll(supplyPumpType1);
        realPlantType.addAll(supplyFlow);
        realPlantType.addAll(supllyFlowNum);
        realPlantType.addAll(nextType);
        realPlantType.addAll(getPump);
        realPlantType.addAll(supplyPumpState);
        realPlantType.addAll(backWind);
        realPlantType.addAll(endType);
        return realPlantType;
    }


    // 初始化推送服务
    private void initPushServise() {
        Intent intent = new Intent(this, PushService.class);
        intent.putExtra(PushService.SERVICE_ACTION, PushService.ACTION_CONNECTION);
        startService(intent);
    }
}
